﻿var mysql = require('C:\\Program Files\\nodejs\\node_modules\\mysql');

exports.excute = function (sqlText, params, callBack) {
    var client = mysql.createClient({
        host:'localhost',
        port:3306,
        user:'root',
        password:'a123456',
        database:'test'
    });

    client.query(
        sqlText,
        params,
        function selectCb(err, results, fields) {
            if (err) {
                console.log(err);
            }
            client.end();
            var json = { err:err, results:results, fields:fields };
            if (callBack) {
                callBack(json);
            }
        });
};

exports.InsertDoubanM = function (json, callBack) {
    var douban = {};
    var subject = json.subject;
    var attribute = subject.attribute;
    var parms =
        [
            douban.SubjectId = subject.nid,
            douban.title = subject.title,
            douban.author = subject.author.name,
            douban.UpdateTs = time(json.updated),
            douban.country = join(attribute.country),
            douban.writer = join(attribute.writer),
            douban.director = join(attribute.director),
            douban.pubdate = time(attribute.pubdate),
            douban.akaCN = subject.title_cn || subject.title,
            douban.rating = json.rating.value,
            douban.summary = json.summary || '',
            douban.cast = join(attribute.cast),
            douban.CollectionId = json.nid,
            douban.imdb = attribute.imdb ? getIdFromUrl(attribute.imdb[0]) : '',
            douban.language = join(attribute.language)
        ];

    var ar = [];
    for (var i = 0; i < parms.length; i++) {
        ar.push('?')
    }

    exports.excute('call test.InsertDoubanM(' + ar.join(',') + ')', parms, callBack);

    function join(ar) {
        return ar ? ar.join('|') : '';
    }

    function time(t) {
        if (Object.prototype.toString.apply(t) === '[object Array]') {
            t = t[0];
        }
        t = new Date(t);
        t.setHours(t.getHours() + 8);
        t = t.toJSON();
        return t ? t.replace('T', ' ').replace('Z', '') : '';
    }
}

function getIdFromUrl(url) {
    if (url) {
        url = url.split('/');
        for (var i = url.length - 1; i > -1; i--) {
            if (url[i]) return url[i];
        }
    }
    return '';
}

